<?php
namespace app\common\service;

use think\facade\Db;

/**
 * @author macheng
 * @group name=WxAppLogin,description=微信小程序登录
 */
class WxAppLogin extends Base
{
    static $AUTH_CHECK = false;

    /**
     * @description 获取绑定信息或互联信息
     * @param string $code 临时登录凭证
     * @param string encryptedData 加密的用户数据 可选
     * @param string iv 加密用数据 可选
     * @return array
     * @return_format  string guid app会员登录唯一标识(已绑定时返回)
     */
    public function index()
    {
        static $AUTH_CHECK = false; //默认必须登录
        $args = input();
        $username = $args['username']??'';
        $password = $args['password']??'';
//        if(!empty($username) && !empty($password)){
//            $rs = Db::name('users')->where('username', $username)->field('user_id,username,password,is_lock')->find();
//            if (encrypt($password) != $rs['password']) {
//                $result = [
//                    'status' => false,
//                    'msg' => '账号和密码错误'
//                ];
//                return $result;
//            }
//            if($rs['is_lock']){
//                $result = [
//                    'status' => false,
//                    'msg' => '账号已锁定，请联系管理员'
//                ];
//                return $result;
//            }
//            $token = logic('UsersLogic')->loginSuccess($rs);
//
//            //返回用户信息
//            $ret = Db::name('users')->where('user_id', $rs['user_id'])->field('user_id,username,head_pic,mobile')->find();
//
//            // guid更新
//            $ret['token'] = $token;
//            $result = [
//                'status' => true,
//                'msg' => '',
//                'data' => $ret
//            ];
//            return $result;
//        }


        $args = input();
        //参数code
        $code = input('code');
        if(!$code) {
            $result = [
                'status' => false,
                'msg' => '参数无效'
            ];
            return $result;
        }


            // 从“微信服务器”获取session_key和open_id
            $appid = tpcache('weixin.wx_app_appid');
            $secret = tpcache('weixin.wx_app_secret');
            if(!$appid || !$secret) {

                $result = [
                    'status' => false,
                    'msg' => '没有配置小程序！请联系管理员！'
                ];
                return $result;
            }
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
            $re = curl_get($url);

            \think\Log::record('WxAppLogin 获取session_key', 'error');
            \think\Log::record($re, 'error');

            $re = json_decode($re, true);
            if(!is_array($re) || !isset($re['openid'])) {
                $errmsg = $re['errmsg'] ?? "";
                $errmsg = "[$code][$errmsg]";
                //abort(500, $errmsg);
                $result = [
                    'status' => false,
                    'msg' => $errmsg
                ];
                return $result;
            }

        $sessionKey = $re['session_key'] ?? '';

        $encryptedData = $args['encryptedData'] ?? '';
        $iv = $args['iv'] ?? '';
        $unionid = '';
        if($sessionKey && $encryptedData && $iv) {
            $data = [];
            $rs = logic('WxApp')->decryptData($encryptedData, $iv, $sessionKey, $data);
            if(!$rs && !empty($data['unionId'])) {
                $unionid = $data['unionId'];
            }
        }

        //不能从微信获取unionid时，从加密参数中解析
        if(empty($re['unionid'])) {
            $re['unionid'] = $unionid;
        }



        //用户资料
        $rawData = input('rawData');
        $rawData_arr = json_decode(htmlspecialchars_decode($rawData,ENT_COMPAT), true);
        $nickname = $rawData_arr['nickName'] ?? input('nickname') ?: ''; //昵称
        $logo = $rawData_arr['avatarUrl'] ?? input('logo') ?: ''; //头像
        $sex = $rawData_arr['gender'] ?? input('sex') ?: 0; //性别

        //签名 验签失败
        /*$signature = $this->params('signature');
        $signature1 = sha1($rawData.$re['session_key']);
        if($signature != $signature1) {
            abort(500,lang('小程序签名失败'));
        }*/

        //是否绑定
        $type = 'weixin';
        $user = logic('SocialLogin')->getBindStatus($type, $re, true);

        if($user) {
            if($username && $username!=$user['username']){
                //当前登录账号和微信已绑定账号不同
                Db::startTrans();
                //解绑微信已绑定账号
                Db::name('social')->where(['user_id' => $user['user_id']])->delete();
                //绑定日志
                Db::name('social_log')->insert(['user_id' => $user['user_id'], 'description' => '切换登录解绑', 'w_time' => getCurTime()]);
                //解绑输入的账号
                //解绑微信已绑定账号
                $now_user = Db::name('users')->where('username',$username)->find();
                Db::name('social')->where(['user_id' => $now_user['user_id']])->delete();
                //绑定日志
                Db::name('social_log')->insert(['user_id' => $now_user['user_id'], 'description' => '切换登录解绑', 'w_time' => getCurTime()]);

                //绑定当前输入的账号
                $token = [];
                $token['openid'] = $re['openid']; //openid
                $token['unionid'] = $re['unionid'] ?? ''; //若有unionid
                $social = [];
                $social['nickname'] = $nickname;
                $social['logo'] = $logo;
                $social['sex'] = $sex ? 1 : 0;
                $user = logic('SocialLogin')->bindUser($username, $type, $token, $social, true, $appid);
                if(!$user['status']){
                    return $user;
                }
                $user['user_id'] = $now_user['user_id'];
                Db::commit();

            }else{
                //更新openid
                $app_openid = Db::name('social')->where(['user_id' => $user['user_id']])->value('app_openid');
                if(!$app_openid) {
                    Db::name('social')->where(['user_id' => $user['user_id']])->setField('app_openid', $re['openid']);
                }
            }

        } else {
            Db::startTrans();
            //已有账号绑定
            if(!empty($args['username'])){
                $username = $args['username'];
                $password = $args['password'];
                $rs = M('users')->where('username', $username)->field('user_id,username,password,is_lock')->find();
                if (encrypt($password) != $rs['password']) {
                    $result = [
                        'status' => false,
                        'msg' => '账号和密码错误'
                    ];
                    return $result;
                }
                if($rs['is_lock']){
                    $result = [
                        'status' => false,
                        'msg' => '账号已锁定，请联系管理员'
                    ];
                    return $result;
                }
            }else{
//                //新建用户
//                $data = [];
//                $data['username'] = logic('User')->getNewUsername(); //获取新编号
//                $data['passwd_one'] = $data['username']; //密码
//                $data['mobile'] = ''; //手机号
//                $data['nickname'] = $nickname;
                $rs = logic('UsersLogic')->createUser();
                $username = $rs['username'];
            }


            //解绑输入的账号
            //解绑微信已绑定账号
            $now_user = Db::name('users')->where('username',$username)->find();
            Db::name('social')->where(['user_id' => $now_user['user_id']])->delete();
            //绑定日志
            Db::name('social_log')->insert(['user_id' => $now_user['user_id'], 'description' => '切换登录解绑', 'w_time' => getCurTime()]);
            //绑定到social表
            $token = [];
            $token['openid'] = $re['openid']; //openid
            $token['unionid'] = $re['unionid'] ?? ''; //若有unionid
            $social = [];
            $social['nickname'] = $nickname;
            $social['logo'] = $logo;
            $social['sex'] = $sex ? 1 : 0;
            $user = logic('SocialLogin')->bindUser($rs['username'], $type, $token, $social, true, $appid);
            Db::commit();
            $user['user_id'] = $user['id'];
        }

        //用户自动登录
        $user['id'] = $user['user_id'];
        $token = logic('UsersLogic')->loginSuccess($user);

        //返回用户信息
        $ret = Db::name('users')->where('user_id', $user['user_id'])->field('user_id,username,head_pic,mobile')->find();

        // guid更新
        $ret['token'] = $token;
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $ret
        ];

        return $result;
    }

    public function bindMobile(){

        $args = input();
        //参数code
        $code = input('code');
        $appid = tpcache('weixin.wx_app_appid');
        $secret = tpcache('weixin.wx_app_secret');

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $re = curl_get($url);
        $re = json_decode($re,true);

        $access_token = $re['access_token'];

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
        $phone_res = curl_post($url,json_encode(['code'=>$code]));
        $phone_res = json_decode($phone_res,true);
        $mobile = $phone_res['phone_info']['phoneNumber'];
        $user_id = input('user_id');
        Db::name('users')->where('user_id',$user_id)->setField('mobile',$mobile);
        $result = [
            'status' => true,
            'msg' => '',
            'data' => '',
        ];

        return $result;



        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $re = curl_get($url);
        $sessionKey = $re['session_key'] ?? '';
        $encryptedData = $args['encryptedData'] ?? '';
        $iv = $args['iv'] ?? '';
        $data = [];
        if($sessionKey && $encryptedData && $iv) {
            $rs = logic('WxApp')->decryptData($encryptedData, $iv, $sessionKey, $data);
        }
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $data,
            'phone_res'=>$phone_res
        ];

        return $result;
    }

}







